﻿using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;

using Xc.DataAccess.Core;
using Xc.DataAccess.HyperTerminalCore.Models;

namespace Xc.DataAccess.HyperTerminalCore.Services
{
    /// <summary>
    /// UDP客户端服务
    /// </summary>
    public class UdpClientService : IUdpClientService
    {
        /// <summary>
        /// UDP 客户端配置信息
        /// </summary>
        public UdpClientOption Option { get; set; }
        /// <summary>
        /// 开启通道
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public async Task<Result> OpenAsync(UdpClientOption option)
        {
            if (Option==null)
            {
                return Result.Reject("请先指定配置信息");
            }
           return await  Task.Run(() => {
                UdpClient udpClient = new UdpClient();
                udpClient.Connect(Option.HostName, option.Port);
               ClientInfo = new UdpClientInfo(udpClient,option.Encoding);
               ClientInfo.BeginRead();
               OnClientJoin?.Invoke(ClientInfo);
                return Result.Accept("建立连接成功");
            });

        }
        /// <summary>
        /// 客户端接入时触发
        /// </summary>
        public event Action<IUdpClientInfo> OnClientJoin;
        public IUdpClientInfo ClientInfo { get;private set; }
        public Result Close()
        {
            ClientInfo.Close();
            return Result.Accept("关闭成功");
        }
    }
}
